package com.java.gulimalltestssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jl
 * Created on 2020/8/20
 */
@Controller
public class HelloController {
    @Value("${ssoServerUrl}")
    private String ssoServerUrl;
    @Value("${ssoServerUserInfUrl}")
    private String ssoServerUserInfUrl;

    /**
     * 无需登录就可访问
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    /**
     * @param token 在ssoserver登录成功后返回
     */
    @GetMapping("/boss")
    public String boss(Model model, HttpSession session, @RequestParam(value = "token",required = false)String token) {
        if (!StringUtils.isEmpty(token)) {
            // 通过token从ssoserver查询已登录的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> entity = restTemplate.getForEntity(ssoServerUserInfUrl + "?token=" + token, String.class);
            String username = entity.getBody();
            session.setAttribute("loginUser",username);
        }

        // 通过查询session中有没有用户信息来判断用户是否登录
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            // 未登录,跳转到登录服务器
            return "redirect:"+ssoServerUrl+"?redirect_url=http://ssoclient2.com:8082/boss";
        }else {
            List<String> employees = new ArrayList<>();
            employees.add("小波");
            employees.add("阿东");
            model.addAttribute("employees",employees);
            return "list";
        }
    }
}
